<template>
  <div class="component-upload-image">
    <el-upload  ref="pictureUpload"
               :action="uploadImgUrl"
               :before-upload="handleBeforeUpload"
               :class="[className,{disabled:uploadDisabled}]"
               :file-list="fileList"
               :headers="headers"
               :on-error="handleUploadError"
               :on-success="handleUploadSuccess"
               :show-file-list="true"
               list-type="picture-card"
               name="file"
    >

      <i slot="default" class="el-icon-plus"></i>
      <div slot="file" slot-scope="{file}">
        <img
            :src="file.url"
            alt="" class="el-upload-list__item-thumbnail"
        >
        <span class="el-upload-list__item-actions">
        <span
            class="el-upload-list__item-delete"
            @click="handleDownload(file)"
        >
        <i class="el-icon-download"></i>
        </span>
        <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
            v-if="!uploadDisabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
      </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" append-to-body title="预览" width="800">
      <img :src="picUrl" alt="" style="display: block; max-width: 100%; margin: 0 auto;"/>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'

export default {
  name: 'ImageUpload',
  data() {
    return {
      accept: 'jpg,jpeg,png,gif,bmp',
      picUrl: null,
      dialogVisible: false,
      uploadImgUrl: process.env.VUE_APP_BASE_API + '/common/upload', // 上传的图片服务器地址
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      fileList: [],
      modelFlag: false
    }
  },
  props: {
    value: {
      type: [String, Array],
      required: false
    },
    className: {
      type: String,
      default: 'IDCard'
    },
    uploadDisabled: {
      type: Boolean,
      default: false
    },
    showList: {
      type: [Array],
      required: false
    }
  },
  watch: {
    value: {
      handler(newVal,oldVal) {
        console.log(newVal)
        if (newVal) {
          if (newVal instanceof Array) {
            if(!this.modelFlag) {
              this.fileList = newVal;
              this.modelFlag = true;
            }
          } else if (newVal instanceof String) {
            this.picUrl = process.env.VUE_APP_BASE_API + newVal
          }
        }
      },
      deep: true
    }
  },
  methods: {
    cancel() {
      this.$refs['pictureUpload'].clearFiles();
    },
    handleUploadSuccess(res) {
      this.picUrl = res.url
      this.$emit('setValue', res, true)
      this.loading.close()
    },
    handleBeforeUpload(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (this.accept.indexOf(fileSuffix) === -1) {
        this.$message({
          type: 'error',
          message: '上传文件只能是' + this.accept + '格式'
        })
        return false
      }
      this.loading = this.$loading({
        lock: true,
        text: '上传中',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    handleUploadError() {
      this.$message({
        type: 'error',
        message: '上传失败'
      })
      this.loading.close()
    },
    handlePictureCardPreview(file) {
      this.picUrl = file.url
      this.dialogVisible = true
    },
    handleDownload(file) {
      window.open(file.url)
    },
    handleRemove(file) {
      let uploadFiles = this.$refs.pictureUpload.uploadFiles
      for (let i = 0; i < uploadFiles.length; i++) {
        if (uploadFiles[i]['url'] == file.url) {
          uploadFiles.splice(i, 1)
        }
      }
      if (file) {
        //this.fileList = this.fileList.filter(ele => ele !== file)
        this.$emit('setValue', file, false)
      }
      this.picUrl = null
      // this.$emit('input', '')
    },
    refreshImage(fileList) {
      this.fileList = fileList
    }
  }
}
</script>

<style lang="scss">
.IDCard {
  .el-upload {
    width: 200px;
    line-height: 126px;
    height: 126px;
  }
}

.file {
  .el-upload {
    width: 200px;
    line-height: 142px;
    height: 142px;
  }
}
</style>
<style lang="scss" scoped>
.image {
  position: relative;
  overflow: hidden;
  width: 100%;
  height: 100%;

  .el-image {
    border-radius: 6px;
  }

  .mask {
    opacity: 0;
    position: absolute;
    top: 0;
    width: 100%;
    background-color: rgba(0, 0, 0, 0.45);
    transition: all 0.3s;

    i {
      margin: 0 10px;
      color: #fff;
      font-size: 20px;
    }
  }

  &:hover .mask {
    opacity: 1;
  }
}
</style>
<style>
.disabled .el-upload--picture-card {
display: none!important;
}

</style>
